<?php

class NewModelsController extends Controller {

    public $defaultAction = 'admin';

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';
    public $menu = [
        //0 =>['label'=>'Список ','url'=>['index'],],
        10 => ['label' => 'Управление ', 'url' => ['admin'],],
        20 => ['label' => 'Создать ', 'url' => ['create'], 'prim' => true],
    ];

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'ajaxdelete', 'ajaxupdate', 'add', 'attach', 'addOne'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAddOne($id) {
        $model = new NewModel();
        $newModel = NewModels::model()->findByPk($id);
        $model->brand = $newModel->brand_title;
        $model->pageTitle = $newModel->model_test_title;
        $cat = Page::model()->findByPk($newModel->cat_id);
        $catUrl = $cat->pageUrl;
        $model->cat_url = $catUrl;
        $model->cat_id = $newModel->cat_id;
        $model->pageUrl = $catUrl . '/' . getUrl::cleanString($newModel->brand_title) . '/' . getUrl::cleanString($newModel->model_test_title);
        $model->pageImages = $newModel->model_image;
        $model->pageType = 'model';
        $model->pageCreateDate = time();
        $this->performAjaxValidation($model);
        if (isset($_POST['NewModel'])) {
            $model->attributes = $_POST['NewModel'];
            $model->pageYandexId = $newModel->model_yandex_id;
            $model->pageSort = $newModel->model_popular;
            $model->pageYandexPrice = $newModel->model_price;
            $model->pageAction = 'list/model';
            if ($model->save()) {
                $newModel->model_status = 'added';
                $newModel->save(false);
                Yii::app()->user->setFlash('save', 'Ваши изменения отправлены на сервер для обновления, они будут доступны пользователям через некоторое время.');
                $this->redirect(array('admin'));
            }
        }

        $this->render('addOne', array('model' => $model));
    }

    public function actionAttach($id) {
        $model = NewModels::model()->findByPk($id);
//        print_r($model);exit;
        if (isset($_POST['from'])) {
            $fromID = json_decode($_POST['from'], 'true');
            $data = array('modelId' => (int) $fromID['id'], 'yandexId' => (int) $id, 'yandexTitle' => $model['model_title']);
            Yii::app()->db->getCommandBuilder()->createInsertCommand('{{model2yandex}}', $data)->execute();
            $model->model_status = 'linked';
            $model->save(false);
            Yii::app()->user->setFlash('save', 'Ваши изменения отправлены на сервер для обновления, они будут доступны пользователям через некоторое время.');
            $this->redirect(array('admin'));
        }
        $this->render('attach', array('model' => $model));
    }

    public function actionAdd() {
//        print_r($_POST);exit;
        if (isset($_POST['name'])) {
            foreach ($_POST['name'] as $key => $name) {
                $brandUrl = getUrl::cleanString($_POST['cat_title'][$key]) . '/' . getUrl::cleanString($_POST['brand'][$key]);
                $sql = 'SELECT "pageTitle", "pageId" FROM {{pages}} WHERE "pageUrl" = LOWER(\'' . strtolower($brandUrl) . '\') AND "pageParent" = ' . $_POST['category'][$key] . ' AND "pageType" = \'brand\'';
                $brand = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryRow();
                if (!empty($brand)) {
                    $parent = $brand['pageId'];
                } else {
                    $data = array(
                        'pageType' => 'brand',
                        'pageAction' => 'list/brand',
                        'pageParent' => $_POST['category'][$key],
                        'pageUrl' => $brandUrl,
                        'pageTitle' => $_POST['brand'][$key]
                    );
                    Yii::app()->db->getCommandBuilder()->createInsertCommand('{{pages}}', $data)->execute();
                    $parent = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{pages}}');
                }
                $modelUrl = $_POST['url'][$key];
                $image = '';
//            print_r($model[7]);exit;
                if (filter_var($_POST['image'][$key], FILTER_VALIDATE_URL)) {
                    if (getimagesize($_POST['image'][$key])) {
                        $image = str_replace('/', '-', $modelUrl) . '.' . pathinfo($_POST['image'][$key], PATHINFO_EXTENSION);
                        copy($_POST['image'][$key], Yii::app()->basePath . '/../uploads/images/model/' . $image);
                    }
                }
                $sql = 'SELECT "pageId" FROM {{pages}} WHERE "pageUrl" = LOWER(\'' . strtolower($modelUrl) . '\') AND "pageType" = \'model\'';
                $modelTitle = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryRow();
                if (!empty($modelTitle))
                    $modelUrl .= '-new';
                $data = array(
                    'pageParent' => $parent,
                    'pageType' => 'model',
                    'pageActive' => 1,
                    'pageAction' => 'list/model',
                    'pageUrl' => $modelUrl,
                    'pageTitle' => pg_escape_string($name),
                    'pageImages' => $image,
                    'pageCreateDate' => time(),
                    'pageYandexId' => $_POST['yandex_id'][$key],
                    'pageYandexPopular' => $_POST['yandex_popular'][$key],
                    'pageYandexPrice' => $_POST['yandex_price'][$key],
                );
                Yii::app()->db->getCommandBuilder()->createInsertCommand('{{pages}}', $data)->execute();
            }
            if (isset($_POST['models'])) {
                $criteria = new CDbCriteria();
                $criteria->addInCondition('row_id', $_POST['models']);
                $data = array('model_status' => 'added');
                Yii::app()->db->getCommandBuilder()->createUpdateCommand('models', $data, $criteria)->execute();
            }
            $this->redirect(array('admin'));
        }
        $this->render('add', array('models' => $_POST['row_id']));
    }

    public function actionAjaxupdate() {
        $act = $_GET['act'];
        $autoIdAll = $_POST['row_id'];
        if (count($autoIdAll) > 0) {
            foreach ($autoIdAll as $autoId) {
                $model = $this->loadModel($autoId);
                if ($act == 'doInactive') {
                    Yii::app()->db->createCommand("UPDATE models SET \"model_status\" = 'rejected' WHERE \"row_id\" = '$autoId'")->execute();
                }
            }
            echo 'ok';
        } else
            throw new Exception("Sorry", 500);
    }

    public function actionAjaxdelete() {
        if (Yii::app()->request->isAjaxRequest) {
            $criteria = new CDbCriteria();
            $criteria->addInCondition('"row_id"', $_POST['row_id']);
            NewModels::model()->deleteAll($criteria);
            echo 'success';
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Page;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Page'])) {
            $model->attributes = $_POST['Page'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->row_id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['NewModels'])) {
            $model->attributes = $_POST['NewModels'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->row_id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('NewModels');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new NewModels('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['NewModels'])) {
            $model->attributes = $_GET['NewModels'];
        }

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return NewModels the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = NewModels::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param NewModels $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'page-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
